import * as echarts5 from 'echarts5'
import request from '@/utils/request'
import { ref } from 'vue'

(function () {
  var Timer = function (elementId, initialTimestamp) {
    this.element = document.getElementById(elementId);
    this.timestamp = initialTimestamp || 0;
    this.intervalId = null;
    this.start(elementId);
  };

  Timer.prototype.start = function (elementId) {
    var self = this;
    this.intervalId = setInterval(function () {
      self.timestamp += 1000; // 每秒增加1000毫秒
      self.render(elementId);
    }, 1000);
  };

  Timer.prototype.stop = function () {
    clearInterval(this.intervalId);
  };

  Timer.prototype.render = function (id) {
    var hours = Math.floor(this.timestamp / (1000 * 60 * 60));
    var minutes = Math.floor((this.timestamp % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((this.timestamp % (1000 * 60)) / 1000);

    hours = (hours < 10) ? '0' + hours : hours;
    minutes = (minutes < 10) ? '0' + minutes : minutes;
    seconds = (seconds < 10) ? '0' + seconds : seconds;

    document.getElementById(id).innerHTML = hours + ':' + minutes + ':' + seconds;
  };

  window.Timer = Timer;
})();


/**
 * 列表
 * @returns {*}
 */
export function list() {
  return request({
    // url: '/cloud/jcce/v1.0/kt1/getConsultationProcess',
    url: '/cloud/jcce/v1.0/kt1/consultationProcess',
    method: 'get'
  })
}

export default {
  name: 'consult',
  data() {
    return {
      dataList: [],
      timerCount: "",
      intervalId: null,
      globalTimer: null,
      timerList: []
    }
  },
  beforeDestroy(){
    this.timerList.forEach(timer => {
      timer.stop();
    })
    clearInterval(this.globalTimer);
    this.globalTimer = null;
  },
  mounted() {
    let self = this
    self.fetchData()
    this.globalTimer = setInterval(()=> {
      self.fetchData()
    }, 10000)
  },
  methods: {
    fetchData() {
      function formatTime(milliseconds) {
        // 将毫秒数转换为秒数
        var seconds = Math.floor(milliseconds / 1000);
        // 计算小时、分钟和秒
        var hours = Math.floor(seconds / 3600);
        seconds %= 3600;
        var minutes = Math.floor(seconds / 60);
        seconds %= 60;

        // 格式化时间
        var formattedTime = pad(hours) + ":" + pad(minutes) + ":" + pad(seconds);
        return formattedTime;
      }

      // 辅助函数，用于将数字转换为两位数的字符串，不足两位的在前面补0
      function pad(num) {
        return ("0" + num).slice(-2);
      }
      list().then((data) => {
        // 获取数据之后重置计时器
        this.timerList.forEach(timer => {
          timer.stop();
        })
        this.timerList = []
        this.dataList = data.data
        this.dataList.forEach((item, index) => {
          if (item.endTime !== null) {
            item.time = formatTime(item.endTime - item.startTime)
            item.timeInfo = "磋商已完成，用时：" + item.time
          }
          else {
            item.time = new Date().getTime() - item.startTime
            item.timeInfo = "磋商进行中，用时："
            let a = new Timer('timer' + index, item.time);
            this.timerList.push(a)
          }
          // this.renderChart(index, item.percentage, "")
        })
      }).catch((error) => {
        console.log(error)
      })
    },
    formatText(item) {
      return () => {
        return `${item.name}`
      }
    },
    getProgressColor(item) {
      if (item.value === 100) {
        return '#17a777'
      } else if (item.value === 0) {
        return '#f8f8fa'
      } else {
        return '#78b79e'
      }
    },
    getProgressTextColor(item) {
      if (item.value === 100) {
        return '#fff'
      } else {
        return '#585a5e'
      }
    },
    checkEnd(item, index) {
      if (item.graphInfos.length === index + 1) {
        return false
      } else {
        return true
      }
    },
    renderChart(index, value, name) {
      const chart = echarts5.init(document.getElementById('chart' + index))
      const gradient = ref({
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [
          {
            offset: 0, color: '#8f97b8' // 0% 处的颜色
          },
          {
            offset: 0.25, color: '#708db9' // 25% 处的颜色
          },
          {
            offset: 0.5, color: '#e2b5e0' // 75% 处的颜色
          },
          {
            offset: 0.75, color: '#8be1d6' // 100% 处的颜色
          },
          {
            offset: 1, color: '#9fe0b4' // 75% 处的颜色
          }
        ],
        global: false // 缺省为 false
      })
      const option = {
        series: [
          {
            type: 'gauge',
            radius: '100%',
            startAngle: 90,
            endAngle: -270,
            pointer: {
              show: false
            },
            progress: {
              show: true,
              overlap: false,
              roundCap: true,
              clip: false,
              itemStyle: {
                borderWidth: 0,
                color: gradient.value
              }
            },
            axisLine: {
              lineStyle: {
                width: 15
              }
            },
            splitLine: {
              show: false,
              distance: 0,
              length: 10
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              show: false,
              distance: 50
            },
            data: [
              {
                value: value,
                name: name,
                title: {
                  offsetCenter: ['0%', '0%']
                },
                detail: {
                  valueAnimation: true,
                  offsetCenter: ['0%', '10%']
                }
              }
            ],
            title: {
              fontSize: 28,
              color: '#5470c6'
            },
            detail: {
              width: 50,
              height: 14,
              fontSize: 30,
              color: 'inherit',
              borderColor: 'inherit',
              borderRadius: 20,
              borderWidth: 0,
              formatter: '{value}%',
              show: (name === '')
            }
          }
        ]
      }
      chart.setOption(option)
    },
    toDetail(item) {
      this.$router.push({
        name: 'consultProcessDetail',
        params: { previousPage: 'consultProcessDetail', isAdd: false, item: item, routeLevel: 3 }
      })
    },
    convertTimestamp(timestamp) {
      var date = new Date(timestamp); // 创建一个新的Date对象
      var year = date.getFullYear(); // 获取年份
      var month = ('0' + (date.getMonth() + 1)).slice(-2); // 获取月份
      var day = ('0' + date.getDate()).slice(-2); // 获取日
      var hours = ('0' + date.getHours()).slice(-2); // 获取小时
      var minutes = ('0' + date.getMinutes()).slice(-2); // 获取分钟
      var seconds = ('0' + date.getSeconds()).slice(-2); // 获取秒
      return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds; // 格式化日期
    }
  }
}
